package com.eblacorp.archive.view.utils;

import java.beans.Introspector;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

public class FacesUtils {

	public static Locale getLocale() {
		try {
			FacesContext context = FacesContext.getCurrentInstance();
			return context.getViewRoot().getLocale();
		} catch (Exception exception) {
			return new Locale("ar_QA");
		}
	}

	public static ServletContext getServletContext() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
		return servletContext;
	}

	public static String getParam(String param) {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> params = context.getExternalContext().getRequestParameterMap();
		return params.get(param);
	}

	public static void setRequestAttr(String key, Object value) {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, Object> attributes = context.getExternalContext().getRequestMap();
		attributes.put(key, value);
	}

	public static Object getRequestAttr(String key) {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, Object> attributes = context.getExternalContext().getRequestMap();
		return attributes.get(key);
	}

	public static Object getSessionAttr(String key) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		return ctx.getExternalContext().getSessionMap().get(key);
	}

	public static void putSessionAttr(String key, Object value) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		Map<String, Object> sessionMap = ctx.getExternalContext().getSessionMap();
		sessionMap.put(key, value);
	}

	public static void addMsg(String msgKey,Severity severity, String additionalMsg) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ResourceBundle bundle = ResourceBundle.getBundle("messages", FacesUtils.getLocale());
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, bundle.getString(msgKey)
				+ additionalMsg, "");
		facesContext.addMessage(null, message);
	}

	public static Object getManagedBean(Class<?> objClass) {
		FacesContext context = FacesContext.getCurrentInstance();
		return context.getApplication().evaluateExpressionGet(context,
				"#{" + Introspector.decapitalize(objClass.getSimpleName()) + "}", objClass);
	}

	public static Object getManagedBean(String expression, Class<?> objClass) {
		FacesContext context = FacesContext.getCurrentInstance();
		return context.getApplication().evaluateExpressionGet(context, "#{" + expression + "}", objClass);
	}

}
